# coding=utf-8
"""
权限验证
author:董新强 日期:2016-01-19
"""
import re

from tornado.gen import coroutine
from tornado.web import RequestHandler

from apis.base_api import BaseHandler
from auth.token_manage import TokenManage
from auth.user_manage import UserManage
from auth.utils import to_int, get_len
from frameworks.resonse_msgs import fail
from pools import run_async

phone_pattern = re.compile('^1\d{10}$')


class LoginHandler(BaseHandler):
    @coroutine
    def post(self):
        if not self.validated: return self.finish(fail(msg='没有权限').response)

        try:
            uid = to_int(self.req_dict.get('uid'))
            client = to_int(self.req_dict.get('client'), 0)
            if not uid:
                return self.finish(fail(msg='参数错误').response)

            result = yield run_async(TokenManage.gen_login_token, self.app_key, uid, client)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='登录失败', hint=str(e)).response)


class Login2Handler(BaseHandler):
    @coroutine
    def post(self):
        if not self.validated: return self.finish(fail(msg='没有权限').response)

        try:
            uid = to_int(self.req_dict.get('uid'))
            client = to_int(self.req_dict.get('client'), 0)
            if not uid:
                return self.finish(fail(msg='参数错误').response)

            result = yield run_async(TokenManage.gen_login_token_with_others, self.app_key, uid, client)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='登录失败', hint=str(e)).response)


class AuthValadeHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            token = self.req_dict.get('token')
            if not token:
                return self.finish(fail(msg='参数错误').response)

            result = yield TokenManage.validate_token(token, self.app_key)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='请登录', hint=str(e)).response)


class UserGetHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            phone = str(self.req_dict.get('phone', ''))
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone_pattern.match(phone)
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone.group()

            result = yield run_async(UserManage.get_user, self.app_key, phone)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='查询用户失败', hint=str(e)).response)


class UserCreateHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            phone = str(self.req_dict.get('phone', ''))
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone_pattern.match(phone)
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone.group()

            result = yield run_async(UserManage.create_usr, self.app_key, phone)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='创建用户失败', hint=str(e)).response)


class RegisterHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            phone = str(self.req_dict.get('phone', ''))
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone_pattern.match(phone)
            if not phone:
                return self.finish(fail(msg='参数错误').response)

            phone = phone.group()

            client = to_int(self.req_dict.get('client'), 0)
            sms_code = to_int(self.req_dict.get('code'), 0)
            if not sms_code:
                return self.finish(fail(msg='验证错误').response)

            pwd = self.req_dict.get('pwd').strip()

            result = yield run_async(UserManage.register_with_sms_code, self.app_key, phone, sms_code, client, pwd)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='创建用户失败', hint=str(e)).response)


class LoginWithWxOpenIdHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            openid = self.req_dict.get('openid', '')
            if not openid:
                return self.finish(fail(msg='参数错误').response)

            result = yield run_async(UserManage.login_with_wx_open_id, self.app_key, openid)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='创建用户失败', hint=str(e)).response)


class ResetPwdHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            client = to_int(self.req_dict.get('client'), 0)
            uid = to_int(self.req_dict.get('uid'))
            pwd = self.req_dict.get('pwd', '').strip()

            if not uid or get_len(pwd) < 6:
                return self.finish(fail(msg='参数错误').response)

            result = yield run_async(UserManage.reset_pwd, self.app_key, uid, pwd, client)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='设置密码失败', hint=str(e)).response)


class OtherHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.set_status(404)

        self.finish()

    def post(self, *args, **kwargs):
        self.set_status(404)
        self.finish()

    def put(self, *args, **kwargs):
        self.set_status(404)
        self.finish()

    def delete(self, *args, **kwargs):
        self.set_status(404)
        self.finish()


class PhoneBindHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            uid = to_int(self.req_dict.get('uid'))
            phone = to_int(self.req_dict.get('phone'))
            code = to_int(self.req_dict.get('code'))
            if not uid or not phone or not code: return self.finish(fail(msg='验证错误').response)

            result = yield run_async(UserManage.phone_bind, self.app_key, uid, phone, code)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='验证失败', hint=str(e)).response)


class EmptyUserCreateHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)
            result = yield run_async(UserManage.create_empey_user, self.app_key)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='创建用户失败', hint=str(e)).response)


class PhoneChangeHandler(BaseHandler):
    """
    更换手机号码
    """

    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            uid = to_int(self.req_dict.get('uid'))
            phone = to_int(self.req_dict.get('phone'))
            if not uid or not phone: return self.finish(fail(msg='参数错误').response)

            result = yield run_async(UserManage.change_phone, self.app_key, uid, phone)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='验证失败', hint=str(e)).response)


class UserInfoUpdateHandler(BaseHandler):
    """
    更换手机号码
    """

    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            uid = to_int(self.req_dict.get('uid'))
            if not uid: return self.finish(fail(msg='参数错误').response)

            result = yield run_async(UserManage.update_user_info, self.app_key, uid, self.req_dict)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='验证失败', hint=str(e)).response)


class UserInfoGetHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            uid = to_int(self.req_dict.get('uid'))
            if not uid: return self.finish(fail(msg='参数错误').response)

            result = yield run_async(UserManage.get_usr_info, self.app_key, uid)
            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='验证失败', hint=str(e)).response)


class UnionChangeHandler(BaseHandler):
    @coroutine
    def post(self):
        try:
            if not self.validated: return self.finish(fail(msg='没有权限').response)

            uid = to_int(self.req_dict.get('uid'))
            union_id = to_int(self.req_dict.get('union_id'))
            if not uid or not union_id: return self.finish(fail(msg='参数错误').response)

            result,uls = yield run_async(UserManage.change_union, self.app_key, uid, union_id)
            if result.is_ok() and uls: yield  UserManage.delete_cache_token(uid,uls)

            self.finish(result.response)
        except Exception as e:
            self.finish(fail(msg='验证失败', hint=str(e)).response)
